﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OpenSoftStore.BusinessLogic.Admin;
using OpenSoftStore.BusinessLogic.Bill;
using OpenSoftStore.BusinessLogic.Common;
using OpenSoftStore.BusinessLogic.Member;
using OpenSoftStore.Client.Common;
using OpenSoftStore.Client.UIL.ManageMember;
using OpenSoftStore.Orm.Model;
using OpenSoftStore.Orm.View;

namespace OpenSoftStore.Client.UIL.ManageBilling
{
    public partial class BillList : UserControl
    {
        private static BillList instance;
        private V_Bill bill;
        public TreeLogic LgcTree;
        public MemberLogic LgcMember;
        public BillLogic LgcBill;
        public AdminLogic LgcAdmin;

        /// <summary>
        /// 返回一个该控件的实例。如果之前该控件已经被创建，直接返回已创建的控件。
        /// 此处采用单键模式对控件实例进行缓存，避免因界面切换重复创建和销毁对象。
        /// </summary>
        public static BillList Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new BillList();
                }
                //BindDataGrid(); // 每次返回该控件的实例前，都将对DataGridView控件的数据源进行重新绑定。
                return instance;
            }
        }

        /// <summary>
        /// 私有的控件实例化方法，创建实例只能通过该控件的Instance属性实现。
        /// </summary>
        private BillList()
        {
            InitializeComponent();
            SPACommon.SetUiStyle(this);
            this.Dock = DockStyle.Fill;
            LgcTree = new TreeLogic();
            LgcMember = new MemberLogic();
            LgcBill = new BillLogic();
            bill = new V_Bill();
            LgcAdmin = new AdminLogic();
            SetUi();
            GetBill();

            SPACommon.SetDataGridStyle(dgvBill);
            SPACommon.SetDataGridStyle(dgvBillItem);
            SPACommon.ShowSummary(dgvBill);
            //cmbShop.DataSource = LgcAdmin.GetShops();
            //cmbShop.DisplayMember = "Name";
            //cmbShop.ValueMember = "Id";

            cmbTime.SelectedIndex = 0;
            cmbState.SelectedIndex = 0;

            btnTree_Add.Visible= SysPowerManager.IsHavePower(SysPowerManager.管理单据分类);
            btnTree_Update.Visible= SysPowerManager.IsHavePower(SysPowerManager.管理单据分类);
            btnTree_Delete.Visible = SysPowerManager.IsHavePower(SysPowerManager.管理单据分类);
            //bool flag = SysPowerManager.IsHavePower(SysPowerManager.撤销单据);
            tsbUpdate.Visible = SysPowerManager.IsHavePower(SysPowerManager.查看单据明细);
            //bool flag = SysPowerManager.IsHavePower(SysPowerManager.打印单据);
            NewMemberAddBill.Visible = SysPowerManager.IsHavePower(SysPowerManager.新客户开单);
            btnRemind.Visible = SysPowerManager.IsHavePower(SysPowerManager.今日客户提醒);
            //bool flag = SysPowerManager.IsHavePower(SysPowerManager.客户退货及结算);
            //bool flag = SysPowerManager.IsHavePower(SysPowerManager.查看退货单);
        }

        private void BillList_Load(object sender, EventArgs e)
        {
            txtBillAdd.Focus();
            txtBillAdd.Select();
          
        }

        private void GetBill()
        {
            dgvBill.AutoGenerateColumns = false;
            dgvBillItem.AutoGenerateColumns = false;

            btnSearch_Click(null,null);
            //dgvBill.DataSource = LgcBill.GetBillView();
            lblDgvGridTotal.Text = dgvBill.Rows.Count.ToString();
        }

        public void SetUi()
        {
            dtFrom.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00");
            dtTo.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59");
            LgcTree.SetTreeNode(LgcTree.GetTreeByType("BillTree"), trTree);
            trTree.SelectedNode = trTree.Nodes[0];
            SPACommon.SetTreeStyle(trTree);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            var memberAddWindow = new MemberAddWindow();
            //memberAddWindow.UcMemberList = this;
            //memberAddWindow.Show();
            memberAddWindow.ShowDialog();
            if (memberAddWindow.DialogResult != DialogResult.OK) return;
            txtBillAdd.Text = memberAddWindow.Tmember.Name;

            string key = txtBillAdd.Text;
            string where = "where T_Member.Name like '{0}%' " +
                           "or T_Member.CardId like '{0}%' " +
                           "or T_Member.CardInsideId like '{0}%' " +
                           "or T_Member.TelNum like '{0}%'";
            where = string.Format(where, key);
            grdMember.DataSource = LgcMember.GetMemberView(where);
            txtBillAdd.Focus();
            //txtBillAdd_KeyDown(null,null);
            // var Page = new TabPage();
            //Page.Name = "Page" + tabControl1.Controls.Count;
            //Page.Text = "tabPage" + tabControl1.Controls.Count;
            //Page.TabIndex = tabControl1.Controls.Count+1;  
            //this.tabControl1.Controls.Add(Page);  

            #region 三种设置某个选项卡为当前选项卡的方法

            //this.tabControl1.SelectedIndex = index;  
            //this.tabControl1.SelectedTab = Page;  
            //this.tabControl1.SelectTab("Page" + index.ToString());  

            #endregion
        }


        private void txtBillAdd_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void txtBillAdd_Load(object sender, EventArgs e)
        {

        }

        private void btnTree_Add_Click(object sender, EventArgs e)
        {
            if (trTree.SelectedNode == null) return;
            trTree.LabelEdit = true;
            var treeNode = new TreeNode { Text = "新子项" };
            TreeNode tnParent = trTree.SelectedNode;
            tnParent.Nodes.Add(treeNode);
            trTree.SelectedNode = treeNode;
            treeNode.BeginEdit();
        }

        private void btnTree_Update_Click(object sender, EventArgs e)
        {
            if (trTree.SelectedNode == null) return;
            trTree.LabelEdit = true;
            trTree.SelectedNode.BeginEdit();
        }

        private void btnTree_Delete_Click(object sender, EventArgs e)
        {
            LgcTree.Delete(trTree);
        }

        private void trTree_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (trTree.SelectedNode == null) return;
            trTree.SelectedNode.EndEdit(true);
            LgcTree.SaveTreeNode(trTree, sender, e, "BillTree");
        }

        private void txtBillAdd_Enter(object sender, EventArgs e)
        {
            grdMember.Height = 300;
            grdMember.Width = 500;
            grdMember.Location = new Point(txtBillAdd.Left, txtBillAdd.Top + txtBillAdd.Height);
            grdMember.Visible =grdMember.RowCount != 0;
        }

        private void txtBillAdd_Leave(object sender, EventArgs e)
        {
            grdMember.Visible = false;
        }

        private void DgvGrid_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvBill.CurrentRow == null) return;
            var id = dgvBill.CurrentRow.Cells["Id"].Value.ToString();
            txtBillNo.Text = dgvBill.CurrentRow.Cells["BillNo"].Value.ToString();
            txtCardId.Text = dgvBill.CurrentRow.Cells["CardId"].Value.ToString();
            txtNeedPay.Text = dgvBill.CurrentRow.Cells["NeedPay"].Value.ToString();
            txtPayTime.Text = dgvBill.CurrentRow.Cells["PayTime"].Value.ToString();
            txtRealPay.Text = dgvBill.CurrentRow.Cells["RealPay"].Value.ToString();

            var data = LgcBill.GetBillItemView(" where BillId = '" + id + "'");
            dgvBillItem.DataSource = null;
            dgvBillItem.DataSource = data;
            lbldgvBillItemTotle.Text = dgvBillItem.Rows.Count.ToString();
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {

        }

        public void btnSearch_Click(object sender, EventArgs e)
        {
            dgvBill.DataSource = null;
            dgvBill.AutoGenerateColumns = false;
            var shopId = cmbShop.SelectedValue.ToString();
            var cardId = txtCardIdx.Text;
            var from = dtFrom.Value;
            var to = dtTo.Value;
            var state = cmbState.Text;
            if (cmbState.Text == "全部") state = "";

            var timeKey = "AddTime";
            if (cmbTime.Text == "结算时间") timeKey="PayTime";
            var code = trTree.SelectedNode.Tag.ToString();
            string where =
                string.Format(" where T_Bill.ShopId like '{0}%' and T_Member.CardId like '{1}%' and T_Bill." + timeKey + " between #{2}# and #{3}# and T_Bill.State like '{4}%' and T_Tree.Code like '" + code + "%'",
                shopId, cardId, from, to, state);
            dgvBill.DataSource = LgcBill.GetBillView(where, " Order By T_Bill.AddTime desc ");
            lblDgvGridTotal.Text = dgvBill.Rows.Count.ToString();
        }

        private void tsbUpdate_Click(object sender, EventArgs e)
        {
            var billAdd = new BillAddWindow();
            if (dgvBill.CurrentRow == null) return;
            var id = dgvBill.CurrentRow.Cells["Id"].Value.ToString();
            billAdd.GetBill(id);
            billAdd.Show();
        }


        private void button6_Click(object sender, EventArgs e)
        {
            string id = LgcMember.SqlWhere<T_Member>(" Name ='" + "临时客户" + "'").ToList()[0].Id;
            var billAdd = new BillAddWindow();
            billAdd.GetMember(id);
            billAdd.Show();
        }

        private void trTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (trTree.SelectedNode.Tag == null) return;
            dgvBill.DataSource = null;
         
            btnSearch_Click(null,null);
            //dgvBill.DataSource = LgcBill.GetBillView(" where T_Tree.Code like '" + code + "%'", " Order By T_Bill.AddTime desc ");
        }

        private void txtBillAdd_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Left || e.KeyCode == Keys.Right)
            {
                if (grdMember.RowCount == 0) return;
                int index, move = 1;
                if (e.KeyCode == Keys.Left) move = -1;
                if (grdMember.CurrentRow == null) index = 0;
                else if (grdMember.CurrentRow.Index + move >= grdMember.RowCount || grdMember.CurrentRow.Index + move < 0)
                    index = 0;
                else index = grdMember.CurrentRow.Index + move;
                if (e.KeyCode == Keys.Left && index == 0) index = 0;
                grdMember.Rows[index].Selected = true; //选中结果所在的行
                grdMember.CurrentCell = grdMember.Rows[index].Cells[0];
                return;
            }
            if (e.KeyCode == Keys.Enter)
            {
                string id = "";
                if (txtBillAdd.Text == "" || txtBillAdd.Text == txtBillAdd.Prompt)
                    id = LgcMember.SqlWhere<T_Member>(" Name ='" + "临时客户" + "'").ToList()[0].Id;
                if (id == "" && (grdMember == null || grdMember.CurrentRow == null)) return;
                var billAdd = new BillAddWindow();
                if (grdMember.CurrentRow != null && id == "")
                    id = grdMember.CurrentRow.Cells["MemberId"].Value.ToString();
                billAdd.GetMember(id);
                grdMember.Visible = false;
                billAdd.Show();
                return;
            }
            if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
            {
                if (grdMember.RowCount == 0) return;
                int index, move = 1;
                if (e.KeyCode == Keys.Up) move = -1;
                if (grdMember.CurrentRow == null) index = 0;
                else if (grdMember.CurrentRow.Index + move >= grdMember.RowCount || grdMember.CurrentRow.Index + move < 0)
                    index = 0;
                else index = grdMember.CurrentRow.Index + move;
                if (e.KeyCode == Keys.Up && index == 0) index = 0;
                grdMember.Rows[index].Selected = true; //选中结果所在的行
                grdMember.CurrentCell = grdMember.Rows[index].Cells[0];
                return;
            }

            if (string.IsNullOrEmpty(txtBillAdd.Text))
            {
                grdMember.DataSource = null;
                return;
            }
            string key = txtBillAdd.Text;
            string where = "where T_Member.Name like '%{0}%' " +
                           "or T_Member.CardId like '%{0}%' " +
                           "or T_Member.CardInsideId like '%{0}%' " +
                           "or T_Member.TelNum like '%{0}%'";
            where = string.Format(where, key);
            grdMember.AutoGenerateColumns = false;
            grdMember.DataSource = LgcMember.GetMemberView(where);
            grdMember.Visible = grdMember.RowCount != 0;

        }

        private void OldMemberAddBill_Click(object sender, EventArgs e)
        {
            string id = LgcMember.SqlWhere<T_Member>(" Name ='" + "临时客户" + "'").ToList()[0].Id;
            var billAdd = new BillAddWindow();
            billAdd.GetMember(id);
            billAdd.Show();
        }

        private void NewMemberAddBill_Click(object sender, EventArgs e)
        {
            var memberAddWindow = new MemberAddWindow();
            //memberAddWindow.UcMemberList = this;
            //memberAddWindow.Show();
            memberAddWindow.ShowDialog();
            if (memberAddWindow.DialogResult != DialogResult.OK) return;
            txtBillAdd.Text = memberAddWindow.Tmember.Name;

            string key = txtBillAdd.Text;
            string where = "where T_Member.Name like '{0}%' " +
                           "or T_Member.CardId like '{0}%' " +
                           "or T_Member.CardInsideId like '{0}%' " +
                           "or T_Member.TelNum like '{0}%'";
            where = string.Format(where, key);
            grdMember.DataSource = LgcMember.GetMemberView(where);
            txtBillAdd.Focus();
            //txtBillAdd_KeyDown(null,null);
            // var Page = new TabPage();
            //Page.Name = "Page" + tabControl1.Controls.Count;
            //Page.Text = "tabPage" + tabControl1.Controls.Count;
            //Page.TabIndex = tabControl1.Controls.Count+1;  
            //this.tabControl1.Controls.Add(Page);  
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {

        }

        private void grdMember_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            string id = "";
            if (txtBillAdd.Text == "" || txtBillAdd.Text == txtBillAdd.Prompt)
                id = LgcMember.SqlWhere<T_Member>(" Name ='" + "临时客户" + "'").ToList()[0].Id;
            if (id == "" && (grdMember == null || grdMember.CurrentRow == null)) return;
            var billAdd = new BillAddWindow();
            if (grdMember.CurrentRow != null && id == "")
                id = grdMember.CurrentRow.Cells["MemberId"].Value.ToString();
            billAdd.GetMember(id);
            billAdd.Show();
        }

        private void btnSearch_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode==Keys.Enter)
            {
                btnSearch_Click(null, null);
            }
        }

        private void btnRemind_Click(object sender, EventArgs e)
        {
            RemindListWindow remindListWindow = new RemindListWindow();
            remindListWindow.ShowDialog();
        }

        private void dgvBill_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex == -1) return;
                var billAdd = new BillAddWindow();
                if (dgvBill.CurrentRow == null) return;
                var id = dgvBill.CurrentRow.Cells["Id"].Value.ToString();
                billAdd.GetBill(id);
                billAdd.Show();
            }
            catch (Exception)
            {
            }
        }

    }
}
